//
//  ResumeDetailVC.m
//  FindJob
//
//  Created by apple on 16/3/13.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "ResumeDetailVC.h"
#import "SelectedTableViewCell.h"
#import "InputTableViewCell.h"
#import "PersonalModel.h"
#import "InfoSelectView.h"
#import "WorkingOfExperienceModel.h"
#import "SaveRusumeInfoAPIManger.h"
#import "TimerView.h"

#import "WaitAlertView.h"

@interface ResumeDetailVC ()<UITableViewDelegate,UITableViewDataSource,InfoSelectViewDataSource,InfoSelectViewDelegate,TimerViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, copy) NSDictionary *dictCell;
@property (nonatomic, copy) NSMutableArray *cellArr;
@property (nonatomic, copy) NSMutableDictionary *dictM;

@property (nonatomic, strong) WaitAlertView *waitView;
@property (nonatomic, strong) TimerView *timerView;
@property (nonatomic, strong) InfoSelectView *selectView;
@property (nonatomic, copy) NSArray *infoDatas;
@property (nonatomic, copy) NSArray *titleKey;
@property (nonatomic, strong) SelectedTableViewCell *selectedCell;

@property (nonatomic, strong) SaveRusumeInfoAPIManger *saveRusumeInfoAPIManger;


- (void)initializeUserIntefcace;  /**< 初始化用户界面 */
- (void)initializeDataSource;     /**< 初始化数据源 */


@end

@implementation ResumeDetailVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
       [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserIntefcace];
}
- (void)initializeDataSource{
    _dictM = [[NSMutableDictionary alloc] init];
}
- (void)initializeUserIntefcace{
    self.navigationItem.title = self.titleName;
   
    [self.tableView reloadData];
    UINib *selectedNib = [UINib nibWithNibName:NSStringFromClass([SelectedTableViewCell class]) bundle:nil];
    [self.tableView registerNib:selectedNib forCellReuseIdentifier:kSelectedCellIdentifier];
    
    UINib *inputNib = [UINib nibWithNibName:NSStringFromClass([InputTableViewCell class]) bundle:nil];
    [self.tableView registerNib:inputNib forCellReuseIdentifier:kInputTableViewCellIdentifier];
}


#pragma mark - notification
- (void)registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(keyboardWasShow:)
                                                name:UIKeyboardDidShowNotification
                                              object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(keyboardWillBeHidden:)
                                                name:UIKeyboardWillHideNotification
                                              object:nil];
}

- (void)unregisterForKeyboardNotifications{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:UIKeyboardDidShowNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:UIKeyboardWillHideNotification
                                                 object:nil];
}

//- (void)keyboardWasShow:(NSNotification *)notification {
//    // 取得键盘的frame，注意，因为键盘在window的层面弹出来的，所以它的frame坐标也是对应window窗口的。
//    CGRect endRect = [[notification.userInfoobjectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//    CGPoint endOrigin = endRect.origin;
//    // 把键盘的frame坐标系转换到与UITextView一致的父view上来。
//    if ([UIApplicationsharedApplication].keyWindow && self.superview) {
//        endOrigin = [self.superview convertPoint:endRect.originfromView:[UIApplicationsharedApplication].keyWindow];
//    }
//    
//    CGFloat adjustHeight = originalContentViewFrame.origin.y + originalContentViewFrame.size.height;
//    // 根据相对位置调整一下大小，自己画图比划一下就知道为啥要这样计算。
//    // 当然用其他的调整方式也是可以的，比如取UITextView的orgin，origin到键盘origin之间的高度作为UITextView的高度也是可以的。
//    adjustHeight -= endOrigin.y;
//    if (adjustHeight > 0) {
//        
//        CGRect newRect = originalContentViewFrame;
//        newRect.size.height -= adjustHeight;
//        [UIView beginAnimations:nil context:nil];
//        self.frame = newRect;
//        [UIView commitAnimations];
//    }
//}

//- (void)keyboardWillBeHidden:(NSNotification *)notification{
//    // 恢复原理的大小
//    [UIViewbeginAnimations:nilcontext:nil];
//    self.frame = originalContentViewFrame;
//    [UIViewcommitAnimations];
//}

#pragma mark - Button

- (IBAction)respondsToSaveBtn:(UIButton *)sender {
   
    
    
    sender.tag = _tag;
    switch (sender.tag) {
        case 10:
        {
             [self.waitView show];
            _titleKey = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"fist1" ofType:@"plist"]];
            NSMutableDictionary *dictM = [self gainDatas:_titleKey];
            NSDictionary *parameter = @{@"personalInfo":dictM,@"personalInfoId":@"0"};
            [self.saveRusumeInfoAPIManger startSavePersonalInfoRequestWithParameters:parameter respons:^(RespondsStatus status, NSString *message, id resultData) {
                if (status == RespondsStatusSuccess) {
                    NSLog(@"%@",message);
//                    [self.waitView hide];
                }else if (status == RespondsStatusDataError){
                    NSLog(@"%@",message);
//                    [self.waitView hide];
                }else{
                    NSLog(@"%@",message);
//                    [self.waitView hide];
                }
                  [self.waitView hide];
            }];
          
        }break;
        case 11:
        {
             [self.waitView show];
            _titleKey = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wofe1" ofType:@"plist"]];
            NSMutableDictionary *dictM = [self gainDatas:_titleKey];
            NSDictionary *parameter = @{@"workExperience":dictM,@"workExperienceId":@"1"};
           [self.saveRusumeInfoAPIManger startSaveWorkExperienceRequestWithParameters:parameter responds:^(RespondsStatus status, NSString *message) {
               if (status == RespondsStatusSuccess) {
                   NSLog(@"%@",message);
                   [self.waitView hide];
               }else if (status == RespondsStatusDataError){
                   NSLog(@"%@",message);
                   [self.waitView hide];
               }else{
                   NSLog(@"%@",message);
                   [self.waitView hide];
               }
           }];
            
        }break;
        case 12:
        {
            
            
        }break;
        case 13:
        {
            
            
        }break;
        case 14:
        {
            
            
        }break;
        case 15:
        {
            
            
        }break;
        default:
            break;
    }
   
}
- (NSMutableDictionary *)gainDatas:(NSArray *)titleKey {
    // indexPath
    for (int i = 0; i < self.datas.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[InputTableViewCell class]]) {
            InputTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            [_dictM setValue:cell.inputTextField.text forKey:titleKey[i]];
            
        }else{
            SelectedTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            [_dictM setValue:cell.subTitle.text forKey:titleKey[i]];
        }
    }
    return _dictM;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dict = self.datas[indexPath.row];
    NSString *key = [dict allKeys][0];
    NSArray *array = dict[key];
    if (array.count == 0) {
        InputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kInputTableViewCellIdentifier];
        cell.titleLabel.text = key;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [_dictCell setValue:cell.inputTextField.text forKey:key];
        [_cellArr addObject:_dictCell];
        return cell;
    }
    SelectedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSelectedCellIdentifier];
    cell.titleLabel.text = key;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.subTitle.text = @"点击选择";
    [_dictCell setValue:cell.subTitle.text forKey:key];
    [_cellArr addObject:_dictCell];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict = self.datas[indexPath.row];
    NSString *key = [dict allKeys][0];
    NSArray *array = dict[key];
    
    if (array.count == 0) {
        InputTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell.inputTextField becomeFirstResponder];
        
    }else if(array.count == 1){
        [self.view addSubview:self.timerView];
        SelectedTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        self.selectedCell = cell;
    }
    
    else{
        self.infoDatas = array;
        if ([self.selectView superview] == nil) {
            [self.view addSubview:self.selectView];
        }
        [self.selectView reloadAllComponents];
        if (self.selectView.numberOfCompents == 0) {
            // 设置默认选择的第一个分区的第0行
            [self infoSelectView:self.selectView didSelectRow:0 inComponent:0];
        }else{
            [self infoSelectView:self.selectView didSelectRow:0 inComponent:1];
        }
    }
}
#pragma mark -- 分区
- (NSInteger)numberOfCompentsInSelectView:(InfoSelectView *)infoSelectView{
    
    NSInteger compents = 1;
    for (id value in self.infoDatas) {
        if ([value isKindOfClass:[NSDictionary class]]) {
            compents = 2;
            break;
        }
    }
    return compents;
}
- (NSInteger)infoSelectView:(InfoSelectView *)infoSelectView numberOfRowsInCompent:(NSInteger)compent{
    if (infoSelectView.numberOfCompents == 2) {
        if (compent == 0) {
            return self.infoDatas.count;
        }
        NSInteger selectIndex =  [infoSelectView selectRowInComponet:0];
        
        NSDictionary *dict = self.infoDatas[selectIndex];
        NSArray *array = dict[@"Cities"];
        return array.count;
        
    }else{
        return self.infoDatas.count;
    }
}

#pragma mark -- UITableViewDelegate
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return CGRectGetHeight(tableView.frame) / self.datas.count;
//}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}
- (NSString *)infoSelectView:(InfoSelectView *)infoSelectView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (infoSelectView.numberOfCompents == 2) {
        
        if (component  == 0) {
            NSDictionary *dict = self.infoDatas[row];
            return dict[@"State"];
        }else{
            // 获取第一个分区选中的行
            NSInteger selectedIndex = [infoSelectView selectRowInComponet:0];
            // 获取选中的字典、选中的哪一行
            NSDictionary *dict = self.infoDatas[selectedIndex];
            NSArray *cities = dict[@"Cities"];
            NSDictionary *cityInfo = cities[row];
            return cityInfo[@"city"];
            
        }
    }else{
        // 只要一个分区是直接返回当前的值
        return self.infoDatas[row];
    }
    
}

- (void)infoSelectView:(InfoSelectView *)infoSelectView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    // 获取选中的cell
    SelectedTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];
    
    if (infoSelectView.numberOfCompents == 2) {
        NSString *subTitle = @"";
        if (component == 0) {
            // 获取选中的字典、选中的哪一行
            NSDictionary *dict = self.infoDatas[row];
            NSArray *cities = dict[@"Cities"];
            NSDictionary *cityInfo = cities[0];
            subTitle = cityInfo[@"city"];
        }else{
            // 获取第一个分区选中的行
            NSInteger selectedIndex = [infoSelectView selectRowInComponet:0];
            // 获取选中的字典、选中的哪一行
            NSDictionary *dict = self.infoDatas[selectedIndex];
            NSArray *cities = dict[@"Cities"];
            NSDictionary *cityInfo = cities[row];
            subTitle = cityInfo[@"city"];
        }
        cell.subTitle.text = subTitle;
        
    }else{
        cell.subTitle.text = self.infoDatas[row];
    }
    
}
#pragma mark - TimerViewDelegate
- (void)timerView:(TimerView *)timerView didSelectedDate:(NSDate *)date{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd(EEEE)"];
    
    self.selectedCell.subTitle.text = [formatter stringFromDate:date];
}

#pragma mark - getters
- (SaveRusumeInfoAPIManger *)saveRusumeInfoAPIManger{
    if (!_saveRusumeInfoAPIManger) {
        _saveRusumeInfoAPIManger = [[SaveRusumeInfoAPIManger alloc] init];
    }
    return _saveRusumeInfoAPIManger;
}
- (NSArray *)datas{
    if (!_datas) {
        _datas = [[NSArray alloc] init];
    }
    return _datas;
}
- (InfoSelectView *)selectView{
    if (!_selectView) {
        _selectView = [[InfoSelectView alloc] initWithDataSoure:self delegate:self];
    }
    return _selectView;
}
- (TimerView *)timerView{
    if (!_timerView) {
        
        _timerView = [[TimerView alloc] initWithDelegate:self];
    }
    return _timerView;
}
- (WaitAlertView *)waitView{
    if (!_waitView) {
        _waitView = [[WaitAlertView alloc] init];
    }
    return _waitView;
}
@end
